package app.myproject.util;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;

public class BlobStoreUtil {
	public static byte[] readURLToByte(String link) {
		try {
			System.out.println("readURLToByte");
			URL url = new URL(link);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream in = conn.getInputStream();
			byte[] b = IOUtils.toByteArray(in);
			in.close();
			return b;
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		return new byte[0];
	}
	public static boolean saveByteToBlob(String name, byte[] data) {
		try {
			System.out.println("saveByteToBlob");

		// Get a file service
		  FileService fileService = FileServiceFactory.getFileService();

		  // Create a new Blob file with mime-type "text/plain"
		  AppEngineFile file = fileService.createNewBlobFile("text/plain",name);

		  // Open a channel to write to it
		  boolean lock = false;
		  FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

		  // Different standard Java ways of writing to the channel
		  // are possible. Here we use a PrintWriter:
		  PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
		  // Close without finalizing and save the file path for writing later
		  out.close();
		  
		  String path = file.getFullPath();
		  // Write more to the file in a separate request:
		  file = new AppEngineFile(path);

		  // This time lock because we intend to finalize
		  lock = true;
		  writeChannel = fileService.openWriteChannel(file, lock);

		  // This time we write to the channel directly
		  writeChannel.write(ByteBuffer.wrap(data));

		  // Now finalize
		  writeChannel.closeFinally();
		  return true;
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	    
	}
}
